package com.wxg.service.impl;

import com.github.pagehelper.PageHelper;
import com.wxg.common.core.dao.mysql.website.User;
import com.wxg.common.core.dao.mysql.website.UserExample;
import com.wxg.dao.mysql.mapper.UserMapper;
import com.wxg.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by void on 2019/6/12.
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User queryByUserName(String userName) {
        UserExample example = new UserExample();
        example.createCriteria().andUsernameEqualTo(userName);
        List<User> users = userMapper.selectByExample(example);
        if(!CollectionUtils.isEmpty(users)){
            return users.iterator().next();
        }
        return null;
    }

    /**
     * 把修改的字段作为查询依据，不断分页会出现问题
     */
    @Transactional
    @Override
    public void tranTest() {
        UserExample example = new UserExample();
        example.createCriteria().andStatusEqualTo(1);

        long total = userMapper.countByExample(example);

        int i = 0;
        int size = 10;
        while (i*size<total){
            PageHelper.startPage(i+1, size);
            List<User> userList = userMapper.selectByExample(example);

            UserExample updateExample = new UserExample();
            updateExample.createCriteria().andUserIdIn(userList.stream().map(User::getUserId).collect(Collectors.toList()));
            User updateUser = new User();
            updateUser.setStatus(0);
            userMapper.updateByExampleSelective(updateUser, updateExample);

            i++;
            log.info("==========执行完第{}次，此时还有{}条未修改的============", i, userMapper.countByExample(example));
        }
        log.info("=========================");
    }
}
